package Section;

import Designation.*;
import connectDB.ConnectDB;
import java.sql.*;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class Sec_View extends javax.swing.JFrame {

    ConnectDB connect = new ConnectDB();

    public Sec_View() {
        connect.getConnect();
        initComponents(); //tạo giao diện
        loadTableDes();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblSect = new javax.swing.JTable();
        btnSectDelete = new javax.swing.JButton();
        btnSectUpdate = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        tblSect.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tblSect.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblSectMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblSect);

        btnSectDelete.setText("Delete");
        btnSectDelete.setEnabled(false);
        btnSectDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSectDeleteActionPerformed(evt);
            }
        });

        btnSectUpdate.setText("Update");
        btnSectUpdate.setEnabled(false);
        btnSectUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSectUpdateActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(btnSectUpdate)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnSectDelete))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(24, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 16, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSectUpdate)
                    .addComponent(btnSectDelete))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 342, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tblSectMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblSectMouseClicked
        // TODO add your handling code here:
        //JOptionPane.showMessageDialog(this, "aaaaa");
        btnSectDelete.setEnabled(true);
        btnSectUpdate.setEnabled(true);
    }//GEN-LAST:event_tblSectMouseClicked

    private void btnSectDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSectDeleteActionPerformed
        deleteSect();
    }//GEN-LAST:event_btnSectDeleteActionPerformed

    private void btnSectUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSectUpdateActionPerformed
        // TODO add your handling code here:
        int choice = tblSect.getSelectedRow();
        String id = tblSect.getValueAt(choice, 0).toString();
        String name = tblSect.getValueAt(choice, 1).toString();
        String inch = tblSect.getValueAt(choice, 2).toString();
        String deptno = tblSect.getValueAt(choice, 3).toString();



        Sec_Update up = new Sec_Update(id);
        loadTableDes();
        up.cbbDepNoUpdate.setSelectedItem(deptno);
        up.setVisible(true);

    }//GEN-LAST:event_btnSectUpdateActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Sec_View.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Sec_View.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Sec_View.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Sec_View.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Sec_View().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSectDelete;
    private javax.swing.JButton btnSectUpdate;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblSect;
    // End of variables declaration//GEN-END:variables

    public void loadTableDes() {
        try {
            String query = "Select * From Sections";
            Statement st = connect.cn.createStatement();
            ResultSet rs = st.executeQuery(query);
            ResultSetMetaData rsmd = rs.getMetaData();
            int numCol = rsmd.getColumnCount();
            Vector nameCol = new Vector();


            for (int i = 1; i <= numCol; i++) {
                nameCol.add(rsmd.getColumnName(i));
            }




            DefaultTableModel dtm = new DefaultTableModel(nameCol, 0);

            while (rs.next()) {

                Vector dataRow = new Vector();
                for (int i = 1; i <= numCol; i++) {
                    dataRow.add(rs.getString(i));
                }
                dtm.addRow(dataRow);
            }
            tblSect.setModel(dtm);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void deleteSect() {
        int j = JOptionPane.showConfirmDialog(this, "Are you sure?", "Yes or No", 0);
        if (j == JOptionPane.YES_OPTION) {
            try {

                String query = "Delete Sections where SECTID = ? ";
                PreparedStatement pst = connect.cn.prepareStatement(query);
                int choice = tblSect.getSelectedRow();
                String id = tblSect.getValueAt(choice, 0).toString();
                pst.setString(1, id);

//            try{
//            String query1 = "Seclect DEPTNO from Sections";
//            Statement st = connect.cn.createStatement();
//            ResultSet rs = st.executeQuery(query1);
//            while(rs.next()){
//                if (tblSect.getValueAt(choice, 0).equals(rs.getString("SECTID"))) {
//                    JOptionPane.showMessageDialog(this, "ID k dc trung");
//                    return;
//                }
//            }
//            }catch(Exception ex) {
//            ex.printStackTrace();
//            JOptionPane.showMessageDialog(this, "abc");
//            return;
//            }
                if (pst.executeUpdate() == -1) {
                    JOptionPane.showMessageDialog(this, "Cannot delete");

                } else {
                    JOptionPane.showMessageDialog(this, "Delete successfully");
                    loadTableDes();
                }

            } catch (Exception ex) {
                //ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "Delete fail");
            }
        }
        if(j==JOptionPane.NO_OPTION){
            JOptionPane.showMessageDialog(this, "Please choose the object that you want to delete, again!!!");
            this.dispose();
                    
        }
    }
}
